window.app = {

	/**
	 * 聊天服务器的地址（Netty）
	 */
	chatServerUrl: 'ws://192.168.101.105:8088/chat',

	/**
	 * 后端服务发布的url地址
	 */
	serverUrl: 'http://192.168.101.105:9090',

	/**
	 * 文件服务器的url地址
	 */
	fileServerUrl: 'http://192.168.101.105:88/rainchat/',

	/**
	 * 判断字符串是否为空
	 * @param {Object} str
	 * true：不为空
	 * false：为空
	 */
	isNotNull: function(str) {
		if (str != null && str != "" && str != undefined) {
			return true;
		}
		return false;
	},

	/**
	 * 封装消息提示框，默认mui的不支持居中和自定义icon，所以使用h5+
	 * @param {Object} msg
	 * @param {Object} type
	 */
	showToast: function(msg, type) {
		plus.nativeUI.toast(msg, {
			icon: "image/" + type + ".png",
			verticalAlign: "center"
		})
	},

	/**
	 * 保存用户的全局对象
	 * @param {Object} user
	 */
	setUserGlobalInfo: function(user) {
		var userInfoStr = JSON.stringify(user);
		plus.storage.setItem("userInfo", userInfoStr);
	},

	/**
	 * 获取用户的全局对象
	 */
	getUserGlobalInfo: function() {
		var userInfoStr = plus.storage.getItem("userInfo");
		return JSON.parse(userInfoStr);
	},

	/**
	 * 登出后，移除用户全局对象
	 */
	logout: function() {
		plus.storage.removeItem("userInfo");
	},

	/**
	 * 保存用户的联系人列表
	 * @param {Object} friendList
	 */
	setFriendList: function(friendList) {
		var friendListStr = JSON.stringify(friendList);
		plus.storage.setItem("friendList", friendListStr);
	},

	/**
	 * 获取本地缓存中的联系人列表
	 */
	getFriendList: function() {
		var friendListStr = plus.storage.getItem("friendList");

		if (!this.isNotNull(friendListStr)) {
			return [];
		}
		return JSON.parse(friendListStr);
	},

	/**
	 * 根据用户id，从本地的缓存（联系人列表）中获取朋友的信息
	 * @param {Object} friendUserId
	 */
	getFriend: function(friendUserId) {
		console.log("friendUserId: " + friendUserId)
		var friendsListStr = plus.storage.getItem("friendList");
		// 判断friendsListStr是否为空
		if (this.isNotNull(friendsListStr)) {
			// 不为空，则把用户信息返回
			var friendsList = JSON.parse(friendsListStr);
			for (var i = 0; i < friendsList.length; i++) {
				var friendsGroup = friendsList[i];
				var friends = friendsGroup.friends;
				if (friends) {
					for (var j = 0; j < friends.length; j++) {
						var friend = friends[j];
						if (friend.friendUserId == friendUserId) {
							return friend;
						}
					}
				}
			}
		} else {
			// 如果为空，直接返回null
			return null;
		}
	},

	/**
	 * 保存用户的聊天记录
	 * @param {Object} unreadMessageList 未读消息列表
	 * @param {Object} ownerId 本人id
	 */
	saveChatHistory: function(unreadMessageList, ownerId) {
		if (!unreadMessageList || !ownerId) {
			return;
		}
		var _this = this;
		for (var i = 0; i < unreadMessageList.length; i++) {
			var unreadMessage = unreadMessageList[i];
			var otherId = unreadMessage.sendUserId; // 朋友id
			var chatKey = "chat-" + ownerId + "-" + otherId;
			// 从本地缓存获取聊天记录是否存在
			var chatHistoryListStr = plus.storage.getItem(chatKey);
			var chatHistoryList;
			if (_this.isNotNull(chatHistoryListStr)) {
				// 如果不为空
				chatHistoryList = JSON.parse(chatHistoryListStr);
			} else {
				// 如果为空，赋一个空的list
				chatHistoryList = [];
			}
			var messageList = unreadMessage.messageList;
			for (var j = 0; j < messageList.length; j++) {
				var message = messageList[j]
				// 构建聊天记录对象
				var type = otherId == message.sendUserId ? 2 : 1;
				var singleMsg = new _this.ChatHistory(message.id, ownerId, otherId, message.message, type);
				// 向list中追加msg对象
				chatHistoryList.push(singleMsg);
			}
			plus.storage.setItem(chatKey, JSON.stringify(chatHistoryList));
		}
	},
	saveOneChatHistory: function(data) {
		var ownerId = data.ownerId; // 本人id
		var otherId = data.otherId; // 朋友id
		var message = data.message;
		var type = data.type;
		if (!ownerId || !otherId || !message || !type) {
			return;
		}
		var _this = this;
		var chatKey = "chat-" + ownerId + "-" + otherId;
		console.log("save key: " + chatKey);
		// 从本地缓存获取聊天记录是否存在
		var chatHistoryListStr = plus.storage.getItem(chatKey);
		var chatHistoryList;
		if (_this.isNotNull(chatHistoryListStr)) {
			// 如果不为空
			chatHistoryList = JSON.parse(chatHistoryListStr);
		} else {
			// 如果为空，赋一个空的list
			chatHistoryList = [];
		}
		var chatHistory = new _this.ChatHistory(new Date().getTime(), otherId, ownerId, message, type);
		// 向list中追加msg对象
		chatHistoryList.push(chatHistory);
		plus.storage.setItem(chatKey, JSON.stringify(chatHistoryList));
	},

	/**
	 * 获取用户聊天记录
	 * @param {Object} userId
	 * @param {Object} friendId
	 */
	getChatHistory: function(userId, friendId) {
		var _this = this;
		var chatKey = "chat-" + userId + "-" + friendId;
		console.log("get key: " + chatKey);
		var chatHistoryListStr = plus.storage.getItem(chatKey);
		var chatHistoryList;
		if (_this.isNotNull(chatHistoryListStr)) {
			// 如果不为空
			chatHistoryList = JSON.parse(chatHistoryListStr);
		} else {
			// 如果为空，赋一个空的list
			chatHistoryList = [];
		}

		return chatHistoryList;
	},

	// 删除我和朋友的聊天记录
	deleteChatHistory: function(userId, friendId) {
		var chatKey = "chat-" + userId + "-" + friendId;
		plus.storage.removeItem(chatKey);
	},

	/**
	 * 聊天记录的快照，仅仅保存每次和朋友聊天的最后一条消息
	 * @param {Object} unreadMessageList 未读消息列表
	 * @param {Object} ownerId 用户id
	 */
	saveChatSnapshot: function(unreadMessageList, ownerId) {
		if (!unreadMessageList || !ownerId) {
			return;
		}
		var _this = this;
		var chatKey = "chat-snapshot-" + ownerId;
		// 从本地缓存获取聊天快照的list
		var chatSnapshotListStr = plus.storage.getItem(chatKey);
		var chatSnapshotList;
		if (_this.isNotNull(chatSnapshotListStr)) {
			// 如果不为空
			chatSnapshotList = JSON.parse(chatSnapshotListStr);
		} else {
			// 如果为空，赋一个空的list
			chatSnapshotList = [];
		}
		for (var i = 0; i < unreadMessageList.length; i++) {
			var unreadMessage = unreadMessageList[i];
			var otherId = unreadMessage.sendUserId; // 好友id
			if (unreadMessage.messageList == null || unreadMessage.messageList.length == 0) {
				continue;
			}
			var otherId = unreadMessage.sendUserId;
			var message = unreadMessage.messageList[unreadMessage.messageList.length - 1];
			// 循环快照list，并且判断每个元素是否包含（匹配）friendId，如果匹配，则删除
			for (var i = 0; i < chatSnapshotList.length; i++) {
				if (chatSnapshotList[i].otherId == otherId) {
					// 删除已经存在的friendId所对应的快照对象
					chatSnapshotList.splice(i, 1);
					break;
				}
			}
			var snapshotMessage = {
				ownerId: ownerId,
				otherId: otherId,
				message: message.message,
				type: message.sendUserId == ownerId ? 1 : 2,
				isRead: false
			}
			console.log(JSON.stringify(snapshotMessage));
			chatSnapshotList.push(snapshotMessage);
		}
		plus.storage.setItem(chatKey, JSON.stringify(chatSnapshotList));
	},
	saveOneChatSnapshot: function(data) {
		var ownerId = data.ownerId;
		var otherId = data.otherId;
		var message = data.message;
		console.log(JSON.stringify(data))
		if (!ownerId || !otherId || !message) {
			return;
		}
		var chatKey = "chat-snapshot-" + ownerId;
		console.log("save key: " + chatKey)
		var _this = this;
		var chatSnapshotListStr = plus.storage.getItem(chatKey);
		var chatSnapshotList;
		if (_this.isNotNull(chatSnapshotListStr)) {
			// 如果不为空
			chatSnapshotList = JSON.parse(chatSnapshotListStr);
			// 循环快照list，并且判断每个元素是否包含（匹配）friendId，如果匹配，则删除
			for (var i = 0; i < chatSnapshotList.length; i++) {
				if (chatSnapshotList[i].otherId == otherId) {
					// 删除已经存在的friendId所对应的快照对象
					chatSnapshotList.splice(i, 1);
					break;
				}
			}
		} else {
			// 如果为空，赋一个空的list
			chatSnapshotList = [];
		}
		chatSnapshotList.push(data);
		plus.storage.setItem(chatKey, JSON.stringify(chatSnapshotList));
	},

	/**
	 * 获取用户快照记录列表
	 */
	getChatSnapshot: function(userId) {
		var _this = this;
		var chatKey = "chat-snapshot-" + userId;
		// 从本地缓存获取聊天快照的list
		var chatSnapshotListStr = plus.storage.getItem(chatKey);
		var chatSnapshotList;
		if (_this.isNotNull(chatSnapshotListStr)) {
			// 如果不为空
			chatSnapshotList = JSON.parse(chatSnapshotListStr);
		} else {
			// 如果为空，赋一个空的list
			chatSnapshotList = [];
		}

		return chatSnapshotList;
	},

	/**
	 * 删除本地的聊天快照记录
	 * @param {Object} ownerId
	 * @param {Object} friendId
	 */
	deleteChatSnapshot: function(ownerId, friendId) {
		var _this = this;
		var chatKey = "chat-snapshot" + ownerId;
		// 从本地缓存获取聊天快照的list
		var chatSnapshotListStr = plus.storage.getItem(chatKey);
		var chatSnapshotList;
		if (_this.isNotNull(chatSnapshotListStr)) {
			// 如果不为空
			chatSnapshotList = JSON.parse(chatSnapshotListStr);
			// 循环快照list，并且判断每个元素是否包含（匹配）friendId，如果匹配，则删除
			for (var i = 0; i < chatSnapshotList.length; i++) {
				if (chatSnapshotList[i].otherId == friendId) {
					// 删除已经存在的friendId所对应的快照对象
					chatSnapshotList.splice(i, 1);
					break;
				}
			}
			plus.storage.setItem(chatKey, JSON.stringify(chatSnapshotList));
		}
	},

	/**
	 * 标记未读消息为已读状态
	 * @param {Object} userId 用户id
	 * @param {Object} friendId 好友id
	 */
	setChatSnapshotReaded: function(userId, friendId) {
		var _this = this;
		var chatSnapshotList = app.getChatSnapshot(userId);
		if (chatSnapshotList.length > 0) {
			for (var i = 0; i < chatSnapshotList.length; i++) {
				var item = chatSnapshotList[i];
				if (item.otherId == friendId) {
					item.isRead = true; // 标记为已读
					chatSnapshotList.splice(i, 1, item); // 替换原有的快照
					var chatKey = "chat-snapshot-" + userId;
					plus.storage.setItem(chatKey, JSON.stringify(chatSnapshotList));
					break;
				}
			}
		}
	},

	/**
	 * 和后端的枚举对应
	 */
	CONNECT: 1, // 第一次(或重连)初始化连接
	CHAT: 2, // 聊天消息
	SIGNED: 3, // 消息签收
	KEEPALIVE: 4, // 客户端保持心跳
	PULL_FRIEND: 5, // 重新拉取好友

	/**
	 * 单个聊天记录的对象
	 * @param {Object} messageId 消息id
	 * @param {Object} ownerId 用户id 
	 * @param {Object} otherId 好友id
	 * @param {Object} msg 消息
	 * @param {Object} type 1-自己发送的，2-好友发送的
	 */
	ChatHistory: function(messageId, ownerId, otherId, message, type) {
		this.messageId = messageId;
		this.ownerId = ownerId;
		this.otherId = otherId;
		this.message = message;
		this.type = type;
	},
	setIsDownloadHistory: function(userId) {
		return plus.storage.setItem("is-download-history-" + userId, "true");
	},
	getIsDownloadHistory: function(userId) {
		return plus.storage.getItem("is-download-history-" + userId);
	},

}
